package com.fancy.mobileschool.service;



import android.util.Log;

import com.fancy.mobileschool.entity.Friend;
import com.fancy.mobileschool.entity.PersonChatMessage;
import com.fancy.mobileschool.util.OKHttpUtil;
import com.fancy.mobileschool.util.GsonUtil;
import com.google.gson.Gson;

import java.util.List;

import okhttp3.FormBody;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;


/**
 * Created by Jackie on 2017/10/21.
 *
 */

public class ChatFriendsService {

    private OkHttpClient httpClient = OKHttpUtil.getHttpClient();

    private Gson gson = GsonUtil.getGson();

    private static final String baseUrl =  URLConfig.baseUrl +  "person_chat";


    public List<Friend> getMyFriends(String myID){
        List<Friend> rs;
        String url = baseUrl + "/getMyFriends.do?myID=" + myID;
        rs = OKHttpBase.fromJsonListByGet(url, Friend.class);
        return rs;
    }

    public List<PersonChatMessage> getMyConversation(String myID, String otherID) {

        List<PersonChatMessage> rs;
        String url = baseUrl + "/getConversation.do?myID=" + myID + "&otherID=" + otherID;
        rs = OKHttpBase.fromJsonListByGet(url, PersonChatMessage.class);
        return rs;
    }

    public PersonChatMessage sendMessage(PersonChatMessage personChatMessage) {
        try {
            FormBody body = new FormBody.Builder()
                    .add("body", gson.toJson(personChatMessage)).build();
            Request request = new Request.Builder().url(baseUrl + "/sendMessage.do").post(body).build();
            Response response = httpClient.newCall(request).execute();
            if (response.code() == 200&&response.body().string().equals("{\"body\":\"OK\"}")){
                return personChatMessage;
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    public List<PersonChatMessage> getNotReadMessage(String myID, String otherID){
        List<PersonChatMessage> rs;
        String url = baseUrl + "/getNotReadMessage.do?myID=" + myID + "&otherID=" + otherID;
        rs = OKHttpBase.fromJsonListByGet(url, PersonChatMessage.class);
        return rs;
    }

    public Friend findFriend(String friendID) {
        Friend friend;
        String url = baseUrl + "/findFriends.do?friendID=" + friendID;
        friend = OKHttpBase.fromJsonByGet(url, Friend.class);
        return friend;
    }

    public void addFriend(String myID, String friendID) {
        try {
            Request request = new Request.Builder().url(baseUrl + "/addFriends.do?person_1=" + myID + "&person_2=" + friendID ).build();
            Response response = httpClient.newCall(request).execute();
            if (response.code() == 200) {
                Log.i("wode","ceee");
            }else {
                Log.i("wode", "eee");
            }

        }catch (Exception e){

        }

    }


}
